package com.cy.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @peoject: yeb
 * @description: 验证码
 * @author: LiShaoZhuo
 * @create: 2021-04-27 17:48
 **/
@RestController
public class KaptchaController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @ApiOperation("验证码")
    @GetMapping(value = "/kaptcha",produces = "image/jpeg")
    public void kaptcha(HttpServletRequest request, HttpServletResponse response){
        //这是固定的方式，直接拷贝就可以
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        //-------------------生成验证码 begin --------------------------
        //获取验证码文本
        String text = defaultKaptcha.createText();
        System.out.println("验证码文本：" + text);
        //将验证码文本放入session
        request.getSession().setAttribute("kaptcha", text);
        //根据验证码文本生成图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream output = null;
        try {
            //输出流输出图片，格式为jpg
            output = response.getOutputStream();
            ImageIO.write(image, "jpg", output);
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (output != null)
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //-------------------生成验证码 end --------------------------
    }
}
